package com.jit.firsthibernate.dao;

import java.util.List;


import org.hibernate.Session;
import org.hibernate.Transaction;

import com.jit.firsthibernate.domain.Profile;
import com.jit.firsthibernate.util.HibernateUtil;

public class ProfileDAO {
	
	private static ProfileDAO instance;
	
	
	private ProfileDAO() {
	}
	
	/**
	 * Create a new account or update an existing one
	 * 
	 * @param profile
	 *            account to be persisted
	 */
	public void saveOrUpdateProfile(Profile profile) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(profile);
		tx.commit();
	}

	/**
	 * Retrieve an account from the data store
	 * 
	 * @param accountId
	 *            identifier of the account to be retrieved
	 * @return account represented by the identifier provided
	 */
	public Profile getProfile(int accountId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		Profile profile = (Profile) session.get(Profile.class, accountId);
		tx.commit();
		return profile;
	}

	/**
	 * Delete account from data store
	 * 
	 * @param profile
	 *            account to be deleted
	 */
	public void deleteProfile(Profile profile) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.delete(profile);
		tx.commit();
	}
	
	public void deleteProfile(int id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.delete((Profile) session.get(Profile.class, id));
		tx.commit();
	}
	
	public List<?> listProfiles() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = session.beginTransaction();
		List<?> profiles = session.createQuery("from Profile").list();
		tx.commit();
		return profiles;
	}
	
	public static ProfileDAO getInstance() {
		if(instance == null) {
			instance = new ProfileDAO(); 	 
		}
		return instance;
	}
}
